﻿/**
@file
@author shockingli
*/

#include "stdafx.h"
#include "ITimer.h"
#include <vector>
#include <set>
#include <list>
#include <utility>
#include <algorithm>
#include "Log.h"
#include "UtilMisc.h"

#include "UtilSys.h"

#define MSG_ASYNC			(WM_USER+123)
#define MSG_START_TIMER		(WM_USER+124)
using std::vector;
using std::pair;
using std::set;
using std::list;
using std::bad_alloc;

#ifdef NOT_USE_IM
	#define TIMERWND_CLASSNAME _T("TXTimer_Class_NOTUSEIM")
#else
	#ifdef SSOPLATFORM
		#define TIMERWND_CLASSNAME _T("TXTimer_Class_SSO")
	#else
		#define TIMERWND_CLASSNAME _T("TXTimer_Class")
	#endif
#endif

namespace
{
	static BOOL IsMainThreadLoopQuit()
	{
		if (!Util::Misc::IsInitAsyncMsgLoop()) return FALSE;

		return Util::Misc::GetMainThreadLoop()?FALSE:TRUE;
	}

	//common
	static PVOID GetMagicFunc(IUnknown * ptr)
	{
		PVOID ** px = (PVOID**)ptr;
		return px[0][3];
	}
	//lorischen add 将一个OnTimer调用使用消息循环分段，防止多个OnTimer事件一次触发，造成卡的情况。
	//static VOID MessageLoopTimer(HWND hwnd)
	//{
	//	MSG msg;
	//	while( ::PeekMessage(&msg,NULL,0,0,PM_REMOVE))
	//	{
	//		if(msg.hwnd == hwnd && msg.message == WM_TIMER)
	//		{
	//			continue; //如果再一次来到OnTimer，不用管，让下一次触发吧
	//		}
	//		if (msg.message == WM_QUIT)
	//		{
	//			PostQuitMessage(0);
	//			return;
	//		}
	//		TranslateMessage(&msg);
	//		DispatchMessage(&msg);
	//	}
	//}

	static bool IsItemValid(IUnknown* pInterface, PVOID pCallFuncAddr)
	{
		__try
		{
			return GetMagicFunc(pInterface) == pCallFuncAddr;
		}
		__except(EXCEPTION_EXECUTE_HANDLER)
		{
			return false;
		}
	}


	struct tagTimerItem
	{
		CComPtr<ITXTimerCallback> pCallback;
		UINT uID;
		UINT uElapse;
		UINT uStart;

		PVOID pCallFuncAddr;
		bool bValid;
		bool bOnce;
		tagTimerItem()
		{
			pCallback = NULL;
			uID = 0;
			uElapse = 0;
			uStart = 0;
			pCallFuncAddr = NULL;
			bValid = FALSE;
			bOnce = FALSE;
		}

		void Init(ITXTimerCallback * pCB, UINT uID, UINT uElapse, bool bOnce)
		{
			this->pCallback = pCB;
			this->uID = uID;
			this->uElapse = uElapse;
			this->uStart = GetTickCount();
			this->pCallFuncAddr = GetMagicFunc(pCB);
			this->bValid = true;
			this->bOnce = bOnce;
		}
	};

	struct tagIdlerItem
	{
		CComPtr<ITXIdleCallback> pCallback;
		PVOID pCallFuncAddr;
		UINT uID;
		bool operator < ( const tagIdlerItem & rhs) const
		{
			if (pCallback != rhs.pCallback)
			{
				return pCallback < rhs.pCallback;
			}
			return uID < rhs.uID;
		}
	};
	struct tagAsyncItem
	{
		CComPtr<ITXAsyncCallback> pCallback;
		PVOID pCallFuncAddr;
		UINT uID;
		bool operator < ( const tagAsyncItem & rhs) const
		{
			if (pCallback != rhs.pCallback)
			{
				return pCallback < rhs.pCallback;
			}
			return uID < rhs.uID;
		}
	};

	class CTimerBase : public base::RefCountedThreadSafe<CTimerBase>
	{
	public:
		HWND m_hWnd;
		LONG m_lLock;
		DWORD m_dwMainThreadId;
		vector<tagIdlerItem> m_setIdlers;
		vector<tagAsyncItem> m_vecAsync;
		typedef vector<tagIdlerItem>::iterator idle_iterator;
		typedef vector<tagAsyncItem>::iterator async_iterator;
		Util::CTXLock			m_lockAsync;
	private:
		friend class base::RefCountedThreadSafe<CTimerBase>;
	public:
		CTimerBase()
		{
			m_hWnd = 0;
			m_lLock = -1;
			m_dwMainThreadId = 0;

			SetupWindow();//在主线程创建窗口		
		}
		virtual ~CTimerBase()
		{
			SetWindowLongPtr(m_hWnd, 0, 0);
			if (::IsWindow(m_hWnd))
			{
				DWORD dwRet;
				::SendMessageTimeout(m_hWnd, WM_CLOSE, 0, 0, SMTO_ABORTIFHUNG, 500, &dwRet);
			}
		}
		virtual LRESULT OnTimer(WPARAM wParam) = 0;
		virtual void StartTimer() = 0;

		//window
		static LRESULT CALLBACK TimerWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
		{
			if (uMsg == WM_CREATE)
			{
				CREATESTRUCT  * cs = (CREATESTRUCT *)lParam;
				SetWindowLongPtr(hWnd, 0, (LONG_PTR)cs->lpCreateParams);
			}
			else if (uMsg == WM_DESTROY)
			{
				SetWindowLongPtr(hWnd, 0, 0);
			}

			CTimerBase* p = NULL;
			if (uMsg == WM_TIMER || uMsg == MSG_ASYNC || uMsg == MSG_START_TIMER)
			{
				LONG_PTR px = GetWindowLongPtr(hWnd, 0);
				if (px)
				{
					p = (CTimerBase*) px;
				}
			}

			if (p)
			{
				if (uMsg == WM_TIMER)
				{
					return p->OnTimer(wParam);
				}
				else if (uMsg == MSG_START_TIMER)
				{
					p->StartTimer();
					return 1;
				}
				else if (uMsg == MSG_ASYNC)
				{
					if (lParam == 0)
					{
						p->CallAsync();
					}
					else
					{
						void (__stdcall * pCallback)(PVOID v) = 0;
						(LPARAM&)pCallback = lParam;
						pCallback((PVOID)wParam);
					}
					return 1;
				}
			}
			return DefWindowProc(hWnd, uMsg, wParam, lParam);
		}

		void SetupWindow()
		{
			if (m_hWnd != 0) return ;
			WNDCLASSEX wc    = {sizeof(wc)};
			wc.hInstance     = GetModuleHandle(0);
			wc.lpszClassName = TIMERWND_CLASSNAME;
			wc.lpfnWndProc   = &TimerWndProc;
			wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
			wc.cbWndExtra    = sizeof(void*);
			RegisterClassEx(&wc);
			m_hWnd = CreateWindowEx(0, wc.lpszClassName, _T("Timer Helper Window"), WS_OVERLAPPED, 0, 0, 100, 100, 
				HWND_MESSAGE, NULL, wc.hInstance, this);
			ShowWindow(m_hWnd, SW_HIDE);
			m_dwMainThreadId = GetCurrentThreadId();
		}

		//idle段。
		BOOL EraseIdleCallback(IN ITXIdleCallback * pCallback, UINT uID)
		{
			BOOL bRet = FALSE;
			m_lockAsync.Lock();
			for(idle_iterator p = m_setIdlers.begin(); p!=m_setIdlers.end(); )
			{
				if (p->pCallback == pCallback && (uID == 0 || uID == p->uID))
				{
					p = m_setIdlers.erase(p);
					bRet = TRUE;
				}
				else
					++ p;
			}
			m_lockAsync.UnLock();

			return bRet;
		}
		BOOL NextIdleCall(IN ITXIdleCallback * pCallback, UINT uID)
		{
			if(!pCallback) return FALSE;
			vector<tagIdlerItem>::iterator it;
			
			m_lockAsync.Lock();
			for (it = m_setIdlers.begin(); it != m_setIdlers.end(); it++ )
			{
				const tagIdlerItem & itm = (*it);
				if (itm.pCallback == pCallback)
				{
					if (uID == 0 || itm.uID == 0 || itm.uID == uID)
					{
						m_lockAsync.UnLock();
						return FALSE;
					}
				}
			}
			tagIdlerItem item = {pCallback, GetMagicFunc(pCallback), uID};
			m_setIdlers.push_back(item);

			m_lockAsync.UnLock();
			return TRUE;
		}
		static bool SafeCallIdle(const tagIdlerItem & item)
		{
			if (IsItemValid(item.pCallback, item.pCallFuncAddr))
			{
#ifdef PerfDef
				CString strTemp;
				strTemp.Format(_T("Addr-0x%x: timmerID %d"),(item.pCallFuncAddr),item.uID);
				AutoTransPerfLog2(L"*.Timmer-Idle"+Util::Perf::AddBracket(strTemp),_T(""),50);
#endif
				
				item.pCallback->OnIdle(item.uID);
				return true;
			}
			return false;
		}
		void NotifyIdle()
		{
			if (! InterlockedIncrement(&m_lLock))
			{
				//idle不能一次只调用一个。
				//否则当队列里积累了几个idle item，且有的会postmessage，有的会再注册 idle时
				//就会不停的有消息，有idle...最后cpu 占用近100%。

				//2010-3-23 先暂时修改为一次只调用一个
				/*
				vector<tagIdlerItem> Idlers = m_setIdlers;
				m_setIdlers.clear();
				std::for_each( Idlers.begin(), Idlers.end(), &SafeCallIdle );
				*/

				tagIdlerItem Idler;
				BOOL bExist = FALSE;

				m_lockAsync.Lock();
				vector<tagIdlerItem>::iterator IdlerIt = m_setIdlers.begin();
				if (IdlerIt != m_setIdlers.end())
				{
					bExist = TRUE;
					Idler = (*IdlerIt);
					m_setIdlers.erase(IdlerIt);
				}	
				m_lockAsync.UnLock();
				
				if (bExist)
					SafeCallIdle(Idler);
			}
			InterlockedDecrement(&m_lLock);
		}

		//async 段。
		BOOL SetAsyncCallback(void (__stdcall*pCallback)(PVOID v), PVOID v)
		{
			if (pCallback && m_hWnd)
			{
				PostMessage(m_hWnd, MSG_ASYNC, (WPARAM)v, (LPARAM)pCallback);
				return TRUE;
			}
			else
			{
				TXASSERT_COND(FALSE);
				return FALSE;
			}
		}
		BOOL SetAsyncCallback(IN ITXAsyncCallback * pCallback, IN OPTIONAL UINT uID)
		{
			if(!pCallback) return FALSE;
			if (!m_hWnd)
			{
				SetupWindow();
			}

			//线程安全
#ifndef VER_FINAL_RELEASE
			if( (m_dwMainThreadId != 0 ) &&  ( GetCurrentThreadId() != m_dwMainThreadId ) )
			{
				//这里不需要再判断了，已经对异步调用加锁处理。
				//MessageBox(NULL, _T("SetAsyncCallback 存在线程安全风险，请改用SetAsyncCallback(void (__stdcall*pCallback)(PVOID v), PVOID v)代替,可联系gavinhuang"), _T("调试期警告"), MB_OK);
			}
#endif

			m_lockAsync.Lock();
			for ( async_iterator it = m_vecAsync.begin(); it != m_vecAsync.end(); it++)
			{
				const tagAsyncItem & itm  = (*it);
				if ((PVOID)itm.pCallback == (PVOID)pCallback)
				{
					if (uID == 0 || itm.uID == 0 || itm.uID == uID)
					{
						m_lockAsync.UnLock();
						return FALSE;
					}
				}
			}
			tagAsyncItem item = {pCallback, GetMagicFunc(pCallback), uID};
			m_vecAsync.push_back(item);

			m_lockAsync.UnLock();

			PostMessage(m_hWnd, MSG_ASYNC, 0, 0);
			return TRUE;
		}
		BOOL EraseAsyncCallback(IN ITXAsyncCallback * pCallback, IN OPTIONAL UINT uID)
		{
			BOOL bRet = FALSE;
			m_lockAsync.Lock();
			for (async_iterator p = m_vecAsync.begin(); p!=m_vecAsync.end(); )
			{
				if ((PVOID)p->pCallback == (PVOID)pCallback && (uID == 0 || uID == p->uID))
				{
					p = m_vecAsync.erase(p);
					bRet = TRUE;
				}
				else
					++ p;
			}
			m_lockAsync.UnLock();
			return bRet;
		}
		static bool SafeCallAsync(const tagAsyncItem & item)
		{
			if (IsItemValid(item.pCallback, item.pCallFuncAddr))
			{
#ifdef PerfDef
				CString strTemp;
				strTemp.Format(_T("Addr-0x%x: timmerID %d"),(item.pCallFuncAddr),item.uID);
				AutoTransPerfLog2(L"*.Timmer-Async"+Util::Perf::AddBracket(strTemp),_T(""),50);
#endif
				

				DWORD T1 = GetTickCount();
				item.pCallback->OnAsyncCall(item.uID);
				DWORD T2 = GetTickCount();
				DWORD dwTimer = T2-T1;

				if ( dwTimer >= PERF_ALERT_TIME )
				{
					TXLog4(L"PerfAsyn.Async",_T("Addr-0x%x,TimerID = %lu,CostTime =%lu"), (item.pCallFuncAddr),item.uID,dwTimer);//21UIN_find_risk++
				}
				return true;
			}
			return false;
		}
		void CallAsync()
		{
			m_lockAsync.Lock();
			vector<tagAsyncItem> items = m_vecAsync;
			m_vecAsync.clear();
			m_lockAsync.UnLock();

			std::for_each(items.begin(), items.end(), &SafeCallAsync);
		}
	};

	class CTimerDetail :public CTimerBase
						
	{
	public:
		enum {TIMER_INIT=1, TIMER_SHORT_ENABLED=2, TIMER_NORMAL_ENABLED=4, TIMER_LONG_ENABLED=8};
		enum {TIMER_SEC0=10, TIMER_SEC1=100, TIMER_SEC2=2000};
		enum {IND_SHORT=0, IND_NORMAL=1, IND_LONG=2};

		DWORD m_dwTimerState;
		enum {TIMER_SHORT_SEGMENT=1024,TIMER_NORMAL_SEGMENT=1024};	//TIMER数组以这个值动态增长，这些值务必要是8的倍数
		tagTimerItem *m_arrShortTimers;								//小timer采用动态数组
		tagTimerItem *m_arrNormalTimers;							//中timer采用动态数组
		vector<tagTimerItem> m_vecLongTimers;						//大timer采用向量容器，遍历比list快，使用比数组方便
		list<tagTimerItem> m_lsCallingTimers;						//符合条件正在调用中的timer。list删除快
		BYTE *m_cShortTable;										//小timer数组的下表索引bit数组
		BYTE *m_cNormalTable;										//小timer数组的下表索引bit数组	
		int m_level;
		DWORD m_dwShortMax;											//当前小timer的最大支持能力
		DWORD m_dwShortUsed;										//当前小timer已使用的个数
		DWORD m_dwNormalMax;										//当前中timer的最大支持能力
		DWORD m_dwNormalUsed;										//当前中timer已使用的个数
		typedef list<tagTimerItem>::iterator timer_iterator;
		base::Lock m_lock;
	public:
		CTimerDetail()
		{
			m_dwTimerState = 0;
			m_level = 0;
			m_dwShortUsed = 0;
			m_dwShortMax = TIMER_SHORT_SEGMENT;
			m_dwNormalUsed = 0;
			m_dwNormalMax = TIMER_NORMAL_SEGMENT;

			m_arrShortTimers = new tagTimerItem[m_dwShortMax];
			m_cShortTable = new BYTE[m_dwShortMax/8];
			memset(m_cShortTable, 0, m_dwShortMax/8);
			memset(m_arrShortTimers, 0, m_dwShortMax*sizeof(tagTimerItem));
			m_arrNormalTimers = new tagTimerItem[m_dwNormalMax];
			m_cNormalTable = new BYTE[m_dwNormalMax/8];
			memset(m_cNormalTable, 0, m_dwNormalMax/8);
			memset(m_arrNormalTimers, 0, m_dwNormalMax*sizeof(tagTimerItem));
		}
		~CTimerDetail()
		{
			delete []m_arrShortTimers;
			m_arrShortTimers=NULL;
			delete []m_cShortTable;
			m_cShortTable=NULL;
			delete []m_arrNormalTimers;
			m_arrNormalTimers=NULL;
			delete []m_cNormalTable;
			m_cNormalTable=NULL;
		}
	public:
		void StartTimer()
		{
			if (m_dwTimerState & TIMER_INIT) return;
			m_dwTimerState |= TIMER_INIT;
			DWORD dwTickCount = GetTickCount();
			//正式初始化、启动Timer机制，把所有已存在的Timer元素结构的起始时间设置成现在
			for (DWORD i = 0; i < m_dwShortMax/8; ++i)
			{
				for (DWORD j = 0; j < 8; ++j)
				{
					if (TRUE == (m_cShortTable[i] & (1<<j)))
					{
						m_arrShortTimers[i*8+j].uStart = dwTickCount;
					}
				}
			}
			for (DWORD i = 0; i < m_dwNormalMax/8; ++i)
			{
				for (DWORD j = 0; j < 8; ++j)
				{
					if (TRUE == (m_cNormalTable[i] & (1<<j)))
					{
						m_arrNormalTimers[i*8+j].uStart = dwTickCount;
					}
				}
			}
			for (vector<tagTimerItem>::iterator it = m_vecLongTimers.begin(); it != m_vecLongTimers.end(); it++)
			{
				it->uStart = dwTickCount;
			}

			VerifyTimer();
		}

		void VerifyTimer()
		{
			if ((m_dwTimerState & TIMER_INIT) == 0)
			{
				SetupWindow();
				PostMessage(m_hWnd, MSG_START_TIMER, 0, 0);
				return ;
			}
			bool b = false;
#define EQ_BOOL(a,b,r) (r=!!(a), r == !!(b))
			//检查是否有小timer，有则创建1个TIMER_SEC0 ms的timer来管理，否则销毁它
			BOOL bHave = FALSE;
			BOOL bBreak = FALSE;
			for (DWORD i = 0; i < m_dwShortMax/8; ++i)
			{
				for (DWORD j = 0; j < 8; ++j)
				{

					if ((m_cShortTable[i] & (1<<j)))
					{
						bHave = TRUE;
						bBreak = TRUE;
						break;
					}
				}
				if (bBreak == TRUE)
				{
					break;
				}
			}
			if (!EQ_BOOL(bHave, m_dwTimerState&TIMER_SHORT_ENABLED, b))
			{
				if (b)
				{
					SetTimer(m_hWnd, 1024, TIMER_SEC0, NULL);//1024号timer管理小timer
					m_dwTimerState |= TIMER_SHORT_ENABLED;
				}
				else
				{
					KillTimer(m_hWnd, 1024);
					m_dwTimerState &= ~TIMER_SHORT_ENABLED;
				}
			}

			//检查是否有中timer，有则创建1个100ms的timer来管理，否则销毁它
			bHave = FALSE;
			bBreak = FALSE;
			for (DWORD i = 0; i < m_dwNormalMax/8; ++i)
			{
				for (DWORD j = 0; j < 8; ++j)
				{

					if ((m_cNormalTable[i] & (1<<j)))
					{
						bHave = TRUE;
						bBreak = TRUE;
						break;
					}
				}
				if (bBreak == TRUE)
				{
					break;
				}
			}
			if (!EQ_BOOL(bHave, m_dwTimerState&TIMER_NORMAL_ENABLED, b))
			{
				if (b)
				{
					SetTimer(m_hWnd, 1025, TIMER_SEC1, NULL);//1025号timer管理中timer
					m_dwTimerState |= TIMER_NORMAL_ENABLED;
				}
				else
				{
					KillTimer(m_hWnd, 1025);
					m_dwTimerState &= ~TIMER_NORMAL_ENABLED;
				}
			}

			//检查大Timer
			if (!EQ_BOOL(m_vecLongTimers.size(), m_dwTimerState&TIMER_LONG_ENABLED, b))
			{
				if (b)
				{
					SetTimer(m_hWnd, 1026, TIMER_SEC2, NULL);
					m_dwTimerState |= TIMER_LONG_ENABLED;
				}
				else
				{
					KillTimer(m_hWnd, 1026);
					m_dwTimerState &= ~TIMER_LONG_ENABLED;
				}
			}
		}


		//根据当前实际情况来调整（扩大、缩小或不变）数组
		BOOL AdjustShortArrayIfNeed()
		{
			//如果需要扩大
			if (m_dwShortUsed+1 > m_dwShortMax)
			{
				try
				{
					tagTimerItem *pNewTimerArray = new tagTimerItem[m_dwShortMax+TIMER_SHORT_SEGMENT];
					BYTE *pNewBitArray = new BYTE[(m_dwShortMax+TIMER_SHORT_SEGMENT)/8];
					//如果没有抛出异常，则可以进行下面工作
					memset(pNewBitArray, 0, (m_dwShortMax+TIMER_SHORT_SEGMENT)/8);
					memset(pNewTimerArray, 0, (m_dwShortMax+TIMER_SHORT_SEGMENT)*sizeof(tagTimerItem));
					//把原来的数据拷贝过来
					for (DWORD i = 0; i < m_dwShortMax; i++)
					{
						pNewTimerArray[i] = m_arrShortTimers[i];
					}
					memcpy(pNewBitArray, m_cShortTable, m_dwShortMax/8);
					delete []m_arrShortTimers;//析构，智能指针引用计数减少
					m_arrShortTimers=NULL;
					delete []m_cShortTable;
					m_cShortTable=NULL;


					m_arrShortTimers = pNewTimerArray;
					m_cShortTable = pNewBitArray;
					m_dwShortMax = m_dwShortMax+TIMER_SHORT_SEGMENT;
				}
				catch (bad_alloc &e)//注意，如果使用MFC库的话，异常会被CMemoryException截获，bad_alloc会截获不到
				{
#ifndef VER_FINAL_RELEASE
					MessageBox(NULL, _T("扩大小timer支持能力时（动态分配内存）失败！"), _T("调试期警告"), MB_OK);
#endif
					return FALSE;
				}
				return TRUE;
			}
			//如果需要缩小
			else if ((m_dwShortMax/TIMER_SHORT_SEGMENT > 1) && ((double)m_dwShortUsed/(double)m_dwShortMax < (double)0.5))//如果利用率不够一半
			{
				try
				{
					DWORD dwNewSize = (m_dwShortUsed + TIMER_SHORT_SEGMENT)/TIMER_SHORT_SEGMENT*TIMER_SHORT_SEGMENT;//取当前使用数往上对齐TIMER_SHORT_SEGMENT的数目
					tagTimerItem *pNewTimerArray = new tagTimerItem[dwNewSize];
					BYTE *pNewBitArray = new BYTE[dwNewSize/8];
					//如果没有抛出异常，则可以进行下面工作
					memset(pNewBitArray, 0, dwNewSize/8);
					memset(pNewTimerArray, 0, dwNewSize*sizeof(tagTimerItem));
					//把原来的数据拷贝过来
					int k = 0;//新数组的索引
					for (DWORD i=0; i<m_dwShortMax/8; ++i)
					{
						for (DWORD j=0; j<8; ++j)
						{
							if (m_cShortTable[i] & (1<<j))//如果有占位
							{
								pNewTimerArray[k] = m_arrShortTimers[i*8+j];
								pNewBitArray[k/8] |= (1<<(k%8));
								k++;
							}
						}
					}
					delete []m_arrShortTimers;
					m_arrShortTimers=NULL;
					delete []m_cShortTable;
					m_cShortTable=NULL;


					m_arrShortTimers = pNewTimerArray;
					m_cShortTable = pNewBitArray;
					m_dwShortMax = dwNewSize;
				}
				catch (bad_alloc &e)
				{
#ifndef VER_FINAL_RELEASE
					MessageBox(NULL, _T("缩小小timer支持能力时（动态分配内存）失败！"), _T("调试期警告"), MB_OK);
#endif
					return TRUE;	//注意这里要返回TRUE，因为还可以使用原来的大数组进行工作
				}
				return TRUE;
			}
			else//不用调整最好了
			{
				return TRUE;
			}
			
		}

		BOOL SetShortTimer(tagTimerItem & item)
		{
			if(10000 <= m_dwShortUsed)
			{
#ifndef VER_FINAL_RELEASE
				MessageBox(NULL, _T("当前设置的小timer已经超过10000个，请检查timer的使用数量！"), _T("调试期警告"), MB_OK);
#endif

			}
			if(FALSE == AdjustShortArrayIfNeed())
			{
				return FALSE;
			}

			int index = -1;
			for (DWORD i=0; i<m_dwShortMax/8; ++i)
			{
				for (DWORD j=0; j<8; ++j)
				{
					if (!(m_cShortTable[i] & (1<<j)))
					{
						if (index == -1)
						{
							index = i*8 + j;//找到第1个空位
						}
					}
					else
					{
						if (m_arrShortTimers[i*8 + j].pCallback == item.pCallback)
						{
							if(item.uID == 0 || item.uID == m_arrShortTimers[i*8 + j].uID) return FALSE;
						}
					}
				}
			}
			if (index != -1)
			{
				m_cShortTable[index/8] |= (1<<(index%8));
				m_arrShortTimers[index] = item;
				m_dwShortUsed++;
				VerifyTimer();
				return TRUE;
			} 
			else
			{
#ifndef VER_FINAL_RELEASE
				MessageBox(NULL, _T("小timer内部出错，请联系开发负责人解决！"), _T("调试期警告"), MB_OK);
#endif
				return FALSE;
			}

		}



		//根据当前实际情况来调整（扩大、缩小或不变）数组
		BOOL AdjustNormalArrayIfNeed()
		{
			//如果需要扩大
			if (m_dwNormalUsed+1 > m_dwNormalMax)
			{
				try
				{
					tagTimerItem *pNewTimerArray = new tagTimerItem[m_dwNormalMax+TIMER_NORMAL_SEGMENT];
					BYTE *pNewBitArray = new BYTE[(m_dwNormalMax+TIMER_NORMAL_SEGMENT)/8];
					//如果没有抛出异常，则可以进行下面工作
					memset(pNewBitArray, 0, (m_dwNormalMax+TIMER_NORMAL_SEGMENT)/8);
					memset(pNewTimerArray, 0, (m_dwNormalMax+TIMER_NORMAL_SEGMENT)*sizeof(tagTimerItem));
					//把原来的数据拷贝过来
					for (DWORD i = 0; i < m_dwNormalMax; i++)
					{
						pNewTimerArray[i] = m_arrNormalTimers[i];
					}
					memcpy(pNewBitArray, m_cNormalTable, m_dwNormalMax/8);
					delete []m_arrNormalTimers;
					delete []m_cNormalTable;
					m_arrNormalTimers = pNewTimerArray;
					m_cNormalTable = pNewBitArray;
					m_dwNormalMax = m_dwNormalMax+TIMER_NORMAL_SEGMENT;
				}
				catch (bad_alloc &e)
				{
#ifndef VER_FINAL_RELEASE
					MessageBox(NULL, _T("扩大中timer支持能力时（动态分配内存）失败！"), _T("调试期警告"), MB_OK);
#endif
					return FALSE;
				}
				return TRUE;
			}
			//如果需要缩小
			else if ((m_dwNormalMax/TIMER_NORMAL_SEGMENT > 1) && ((double)m_dwNormalUsed/(double)m_dwNormalMax < (double)0.5))//如果利用率不够一半
			{
				try
				{
					DWORD dwNewSize = (m_dwNormalUsed + TIMER_NORMAL_SEGMENT)/TIMER_NORMAL_SEGMENT*TIMER_NORMAL_SEGMENT;//取当前使用数往上对齐TIMER_NORMAL_SEGMENT的数目
					tagTimerItem *pNewTimerArray = new tagTimerItem[dwNewSize];
					BYTE *pNewBitArray = new BYTE[dwNewSize/8];
					//如果没有抛出异常，则可以进行下面工作
					memset(pNewBitArray, 0, dwNewSize/8);
					memset(pNewTimerArray, 0, dwNewSize*sizeof(tagTimerItem));
					//把原来的数据拷贝过来
					int k = 0;//新数组的索引
					for (DWORD i=0; i<m_dwNormalMax/8; ++i)
					{
						for (DWORD j=0; j<8; ++j)
						{
							if (m_cNormalTable[i] & (1<<j))//如果有占位
							{
								pNewTimerArray[k] = m_arrNormalTimers[i*8+j];
								pNewBitArray[k/8] |= (1<<(k%8));
								k++;
							}
						}
					}
					delete []m_arrNormalTimers;
					delete []m_cNormalTable;
					m_arrNormalTimers = pNewTimerArray;
					m_cNormalTable = pNewBitArray;
					m_dwNormalMax = dwNewSize;
				}
				catch (bad_alloc &e)
				{
#ifndef VER_FINAL_RELEASE
					MessageBox(NULL, _T("缩小中timer支持能力时（动态分配内存）失败！"), _T("调试期警告"), MB_OK);
#endif
					return TRUE;	//注意这里要返回TRUE，因为还可以使用原来的大数组进行工作
				}
				return TRUE;
			}
			else//不用调整最好了
			{
				return TRUE;
			}

		}


		BOOL SetNormalTimer(tagTimerItem & item)
		{
			if(10000 <= m_dwNormalUsed)
			{
#ifndef VER_FINAL_RELEASE
				MessageBox(NULL, _T("当前设置的中timer已经超过10000个，请检查timer的使用数量！"), _T("调试期警告"), MB_OK);
#endif

			}
			if(FALSE == AdjustNormalArrayIfNeed())
			{
				return FALSE;
			}

			int index = -1;
			for (DWORD i=0; i<m_dwNormalMax/8; ++i)
			{
				for (DWORD j=0; j<8; ++j)
				{
					if (!(m_cNormalTable[i] & (1<<j)))
					{
						if (index == -1)
						{
							index = i*8 + j;//找到第1个空位
						}
					}
					else
					{
						if (m_arrNormalTimers[i*8 + j].pCallback == item.pCallback)
						{
							if(item.uID == 0 || item.uID == m_arrNormalTimers[i*8 + j].uID) return FALSE;
						}
					}
				}
			}
			if (index != -1)
			{
				m_cNormalTable[index/8] |= (1<<(index%8));
				m_arrNormalTimers[index] = item;
				m_dwNormalUsed++;
				VerifyTimer();
				return TRUE;
			} 
			else
			{
#ifndef VER_FINAL_RELEASE
				MessageBox(NULL, _T("中timer内部出错，请联系开发负责人解决！"), _T("调试期警告"), MB_OK);
#endif
				return FALSE;
			}

		}
		BOOL SetLongTimer(tagTimerItem & item)
		{
			//先检查
			for (vector<tagTimerItem>::iterator it = m_vecLongTimers.begin(); it != m_vecLongTimers.end(); ++it)
			{
				if (it->pCallback == item.pCallback)
				{
					if(item.uID == 0 || item.uID == it->uID) return FALSE;
				}
			}
			m_vecLongTimers.push_back(item);
			VerifyTimer();
			return TRUE;
		}

		BOOL SetCommon(tagTimerItem & item)
		{
			if (item.uElapse == 0)
			{
				item.uElapse = TIMER_SEC1;
			}
			if (item.uElapse <= TIMER_SEC1*180/100)
			{
				return SetShortTimer(item);
			}
			else if ((TIMER_SEC1*180/100 < item.uElapse) && (item.uElapse <= 35*TIMER_SEC2))
			{
				return SetNormalTimer(item);
			}
			else
			{
				return SetLongTimer(item);
			}
		}
		BOOL SetInterval(IN UINT uElapse, IN ITXTimerCallback * pCallback, IN OPTIONAL UINT uID/* = 0*/)
		{
			base::AutoLock lock(m_lock);

			//线程安全
#ifndef VER_FINAL_RELEASE
			if( (m_dwMainThreadId != 0 ) &&  ( GetCurrentThreadId() != m_dwMainThreadId ) )
			{
				MessageBox(NULL, _T("SetInterval 存在线程安全风险，可联系gavinhuang"), _T("调试期警告"), MB_OK);
			}
#endif
			if(!pCallback) return FALSE;
			tagTimerItem item;
			item.Init(pCallback, uID, uElapse, false);
			return SetCommon(item);
		}
		BOOL SetTimeout(IN int uElapse, IN ITXTimerCallback * pCallback, IN OPTIONAL UINT uID/* = 0*/)
		{
			base::AutoLock lock(m_lock);

			//线程安全
#ifndef VER_FINAL_RELEASE
			if( (m_dwMainThreadId != 0 ) &&  ( GetCurrentThreadId() != m_dwMainThreadId ) )
			{
				MessageBox(NULL, _T("SetInterval 存在线程安全风险，可联系gavinhuang"), _T("调试期警告"), MB_OK);
			}
#endif
			if(!pCallback) return FALSE;
			tagTimerItem item;
			item.Init(pCallback, uID, uElapse, true);
			return SetCommon(item);
		}



		BOOL EraseTimerCallback(IN ITXTimerCallback * pCallback, IN OPTIONAL UINT uID=0)
		{
			base::AutoLock lock(m_lock);

			BOOL bRet = FALSE;//只要有删除成功1个timer，就可以置之TRUE
			for (DWORD i=0; i<m_dwShortMax/8; ++i)
			{
				for (DWORD j=0; j<8; ++j)
				{
					if ((m_cShortTable[i] & (1<<j)))
					{
						if (m_arrShortTimers[i*8+j].pCallback == pCallback && (uID == 0 || m_arrShortTimers[i*8+j].uID == uID))
						{
							m_arrShortTimers[i*8+j].pCallback = NULL;		//引用计数减少
							m_arrShortTimers[i*8+j].pCallFuncAddr = NULL;	//只是个地址，但是为了严谨，也置空
							m_cShortTable[i] &= ~(1<<j);
							m_dwShortUsed--;
							bRet = TRUE;
						}
					}
				}
			}
			for (DWORD i=0; i<m_dwNormalMax/8; ++i)
			{
				for (DWORD j=0; j<8; ++j)
				{
					if ((m_cNormalTable[i] & (1<<j)))
					{
						if (m_arrNormalTimers[i*8+j].pCallback == pCallback && (uID == 0 || m_arrNormalTimers[i*8+j].uID == uID))
						{
							m_arrNormalTimers[i*8+j].pCallback = NULL;		//引用计数减少
							m_arrNormalTimers[i*8+j].pCallFuncAddr = NULL;	//只是个地址，但是为了严谨，也置空
							m_cNormalTable[i] &= ~(1<<j);
							m_dwNormalUsed--;
							bRet = TRUE;
						}
					}
				}
			}
			for (vector<tagTimerItem>::iterator it = m_vecLongTimers.begin(); it != m_vecLongTimers.end(); )
			{
				if (it->pCallback == pCallback && (uID == 0 || it->uID == uID))
				{
					it = m_vecLongTimers.erase(it);
					bRet = TRUE;
				}
				else
				{
					++ it;
				}
			}

			//检查正在调用中的timer是否有刚刚删除的timer，如果有，则置之无效，后续不会调用
			{
				base::AutoLock lock(m_lock); 
				for (timer_iterator it = m_lsCallingTimers.begin(); it != m_lsCallingTimers.end(); it++)
				{
					if (it->pCallback == pCallback && (uID == 0 || it->uID == uID))
					{
						it->bValid = false;
					}
				}
			}
			VerifyTimer();

			return bRet;
		}



		void Call(tagTimerItem &item)
		{
			if (item.bValid)
			{
				//call.
				if (IsItemValid(item.pCallback, item.pCallFuncAddr))
				{
					//下面这段关于性能评估的代码，其实是严重影响性能的。在我机器上，有它是12%的占用率，没则是0%。
// #ifdef PerfDef
// 					CString strTemp;
// 					strTemp.Format(_T("Addr-0x%x timmerID %d"),(item.pCallFuncAddr),item.uID);
// 					AutoTransPerfLog2(L"*.Timmer-OnTimmer"+Util::Perf::AddBracket(strTemp),_T(""),50);					
// #endif
					//MessageLoopTimer(m_hWnd);
					item.pCallback->OnTimer(item.uID);
				}
			}
		}



		LRESULT OnTimer(WPARAM wParam)
		{
			int level = ++ m_level;

			DWORD dwTick = GetTickCount();

			if (wParam == 1024)
			{
				for (DWORD i=0; i<m_dwShortMax/8; ++i)
				{
					for (DWORD j=0; j<8; ++j)
					{
						if ((m_cShortTable[i] & (1<<j)))
						{
							if (dwTick - m_arrShortTimers[i*8+j].uStart >= m_arrShortTimers[i*8+j].uElapse)
							{
								if (IsItemValid(m_arrShortTimers[i*8+j].pCallback, m_arrShortTimers[i*8+j].pCallFuncAddr))
								{
									// m_lsCalling非线程安全: leezyli 2012/5/18
									base::AutoLock lock(m_lock); 

									m_arrShortTimers[i*8+j].uStart = dwTick;
									m_lsCallingTimers.push_back(m_arrShortTimers[i*8+j]);
									if (m_arrShortTimers[i*8+j].bOnce)
									{
										m_arrShortTimers[i*8+j].pCallback = NULL;		//引用计数减少
										m_arrShortTimers[i*8+j].pCallFuncAddr = NULL;	//只是个地址，但是为了严谨，也置空
										m_cShortTable[i] &= ~(1<<j);
										m_dwShortUsed--;
									}
								}
								else
								{
									m_arrShortTimers[i*8+j].pCallback = NULL;		//引用计数减少
									m_arrShortTimers[i*8+j].pCallFuncAddr = NULL;	//只是个地址，但是为了严谨，也置空
									m_cShortTable[i] &= ~(1<<j);
									m_dwShortUsed--;
								}
							}
						}
					}
				}

				//开始回调
				while (!m_lsCallingTimers.empty())
				{
					//要先删除，再调用。否则在重入的情况下可能会造成重复调用
					tagTimerItem ti;
					{
						// m_lsCalling非线程安全: leezyli 2012/5/18
						base::AutoLock lock(m_lock); 
						if(!m_lsCallingTimers.empty())
						{
							ti = *(m_lsCallingTimers.begin());
							m_lsCallingTimers.pop_front();
						}
					}
					
					Call(ti);
					if (level != m_level)
					{
						//发生了重入。迭代器已无效
// #ifndef VER_FINAL_RELEASE
// 						MessageBox(NULL, _T("发生了重入，请不要在Timer回调函数里DoModal"), _T("调试期警告"), MB_OK);
// #endif
						return 1;
					}
				}
			}
			else if (wParam == 1025)
			{
				for (DWORD i=0; i<m_dwNormalMax/8; ++i)
				{
					for (DWORD j=0; j<8; ++j)
					{
						if ((m_cNormalTable[i] & (1<<j)))
						{
							if (dwTick - m_arrNormalTimers[i*8+j].uStart >= m_arrNormalTimers[i*8+j].uElapse)
							{
								if (IsItemValid(m_arrNormalTimers[i*8+j].pCallback, m_arrNormalTimers[i*8+j].pCallFuncAddr))
								{
									// m_lsCalling非线程安全: leezyli 2012/5/18
									base::AutoLock lock(m_lock); 

									m_arrNormalTimers[i*8+j].uStart = dwTick;
									m_lsCallingTimers.push_back(m_arrNormalTimers[i*8+j]);
									if (m_arrNormalTimers[i*8+j].bOnce)
									{
										m_arrNormalTimers[i*8+j].pCallback = NULL;		//引用计数减少
										m_arrNormalTimers[i*8+j].pCallFuncAddr = NULL;	//只是个地址，但是为了严谨，也置空
										m_cNormalTable[i] &= ~(1<<j);
										m_dwNormalUsed--;
									}
								}
								else
								{
									m_arrNormalTimers[i*8+j].pCallback = NULL;		//引用计数减少
									m_arrNormalTimers[i*8+j].pCallFuncAddr = NULL;	//只是个地址，但是为了严谨，也置空
									m_cNormalTable[i] &= ~(1<<j);
									m_dwNormalUsed--;
								}
							}
						}
					}
				}

				//开始回调
				while (!m_lsCallingTimers.empty())
				{
					//要先删除，再调用。否则在重入的情况下可能会造成重复调用
					tagTimerItem ti;
					{
						// m_lsCalling非线程安全: leezyli 2012/5/18
						base::AutoLock lock(m_lock);
						if(!m_lsCallingTimers.empty())
						{
							ti = *(m_lsCallingTimers.begin());
							m_lsCallingTimers.pop_front();
						}
					}

					Call(ti);
					if (level != m_level)
					{
						//发生了重入。迭代器已无效
// #ifndef VER_FINAL_RELEASE
// 						MessageBox(NULL, _T("发生了重入，请不要在Timer回调函数里DoModal"), _T("调试期警告"), MB_OK);
// #endif
						return 1;
					}
				}
			}
			else if (wParam == 1026)
			{
				//这里必须用另外的vector把符合条件回调的timer保存起来，而不能直接用m_vecLongTimers进行回调。因为如果用户
				//的OnTimer函数有EraseTimerCallback操作，则会破坏当前的迭代器，导致无法迭代下去。
				for (vector<tagTimerItem>::iterator it = m_vecLongTimers.begin(); it!=m_vecLongTimers.end(); )
				{
					if (dwTick - it->uStart >= it->uElapse)
					{
						if (IsItemValid(it->pCallback, it->pCallFuncAddr))
						{
							// m_lsCalling非线程安全: leezyli 2012/5/18
							base::AutoLock lock(m_lock); 
							m_lsCallingTimers.push_back(*it);
							it->uStart = dwTick;
							if (it->bOnce)
							{
								it = m_vecLongTimers.erase(it);
							}
							else
							{
								it++;
							}
						}
						else
						{
							// m_lsCalling非线程安全: leezyli 2012/5/18
							base::AutoLock lock(m_lock); 
							it = m_vecLongTimers.erase(it);
						}
					}
					else
					{
						it++;
					}
				}

				//开始回调
				while (!m_lsCallingTimers.empty())
				{
					//要先删除，再调用。否则在重入的情况下可能会造成重复调用
					tagTimerItem ti;
					{
						// m_lsCalling非线程安全: leezyli 2012/5/18
						base::AutoLock lock(m_lock);
						if(!m_lsCallingTimers.empty())
						{						
							ti = *(m_lsCallingTimers.begin());
							m_lsCallingTimers.pop_front();
						}
					}
					
					Call(ti);
					if (level != m_level)
					{
						//发生了重入。迭代器已无效
// #ifndef VER_FINAL_RELEASE
// 						MessageBox(NULL, _T("发生了重入，请不要在Timer回调函数里DoModal"), _T("调试期警告"), MB_OK);
// #endif
						return 1;
					}
				}

			}

			return TRUE;
		}
	};
}

#include "map"
using namespace std;
map<DWORD,scoped_refptr<CTimerDetail> > g_mapThreadToTime;
base::Lock g_Lock;

static void DestroyTimer()
{
	base::AutoLock lock(g_Lock);
	g_mapThreadToTime.clear();
}

static CTimerDetail* FindTimerInst(DWORD dwId)
{
	base::AutoLock lock(g_Lock);
	map<DWORD,scoped_refptr<CTimerDetail> >::iterator it;
	
	it = g_mapThreadToTime.find(dwId);
	if (it != g_mapThreadToTime.end())
	{
		return it->second;
	}
	
	return NULL;
}

//恢复InitTimer,防止Timer对象太晚析构,
//导致QQ插桩退出时crash. @9358953 toddchen. 
static void InitTimer()
{
	Util::Misc::AddToDeadQueue(Util::Misc::DEADQUEUE_PRIORITY_BEF_EXIT_WINMAIN, DestroyTimer);
}
extern "C" void * e_txweakobj_7 = InitTimer;

#ifdef VER_FINAL_RELEASE
	#define TXTimerThreadWarnning()
#else
	#define TXTimerThreadWarnning() \
	do { \
		DWORD dwThreadId = GetCurrentThreadId(); \
		TCHAR szCaption[16] = {0}; \
		_stprintf_s(szCaption, 16, _T("调试期警告 %d"), dwThreadId); \
		MessageBox(NULL, _T("非UI线程和逻辑线程的Timer无效"), szCaption, MB_OK); \
	} while(0)
#endif

namespace TXTimer
{
    scoped_refptr<CTimerDetail> GetInst(DWORD dwThreadID)
	{
		/*(g_pTD != NULL);
		return g_pTD;*/
		//g_Lock.ReadLock();
		base::AutoLock lock(g_Lock);
		map<DWORD,scoped_refptr<CTimerDetail> >::iterator it = g_mapThreadToTime.find(dwThreadID);
		if(it != g_mapThreadToTime.end())
		{		
			scoped_refptr<CTimerDetail> pTemp = it->second.get();
			//g_Lock.ReadUnLock();
		    return pTemp;		
		}
		else
		{			
			//g_Lock.ReadUnLock();
			scoped_refptr<CTimerDetail> pTD = new CTimerDetail();

			//g_Lock.WriteLock();
			g_mapThreadToTime[dwThreadID] = pTD;
			//g_Lock.WriteUnLock();
			
			return pTD;
		}
	}

	/** 设置一个多次调用的Timer, 通过pCallback调回。
	*  当同一个pCallback要根据uID参数设置多个回调时，任意一个uID都不得为0
	*
	*	@param pCallback   in, 回调接口
	*	@param uElapse      in, timer时间间隔值
	*  @param uID          in, optional, 设置一个ID值。
	*
	*	@retval TRUE		成功
	*	@retval FALSE		失败
	*/
	BOOL SetInterval(IN UINT uElapse, IN ITXTimerCallback * pCallback, IN OPTIONAL UINT uID)
	{
		DWORD dwUIThreadId,dwLogicThreadId,dwCurrentThreadId;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		dwCurrentThreadId = GetCurrentThreadId();

		if(dwCurrentThreadId != dwUIThreadId && dwCurrentThreadId != dwLogicThreadId)
		{
			TXTimerThreadWarnning();
			return FALSE;
		}
		else
		{
			return GetInst(dwCurrentThreadId)->SetInterval(uElapse, pCallback, uID);
		}
	}
	/** 设置一个单次调用的Timer, 通过pCallback调回。
	*  当同一个pCallback要根据uID参数设置多个回调时，任意一个uID都不得为0
	*
	*	@param pCallback   in, 回调接口
	*	@param uElapse      in, timer时间间隔值
	*  @param uID          in, optional, 设置一个ID值。
	*
	*	@retval TRUE		成功
	*	@retval FALSE		失败
	*/
	BOOL SetTimeout(IN UINT uElapse, IN ITXTimerCallback * pCallback, IN OPTIONAL UINT uID)
	{
		DWORD dwUIThreadId,dwLogicThreadId,dwCurrentThreadId;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		dwCurrentThreadId = GetCurrentThreadId();

		if(dwCurrentThreadId != dwUIThreadId && dwCurrentThreadId != dwLogicThreadId)
		{
			TXTimerThreadWarnning();
			return FALSE;
		}
		else
		{
			return GetInst(dwCurrentThreadId)->SetTimeout(uElapse, pCallback, uID);
		}
	}
	/** 注销一个已经设置的Timer Callback
	*
	*	@param pCallback   in, 回调接口
	*  @param uID          in, optional, 对应要取消的ID值。\n
	*                      当uID为0时，注销该回调接口的所有回调id。
	*
	*	@retval TRUE		成功
	*	@retval FALSE		失败
	*/
	BOOL EraseTimerCallback(IN ITXTimerCallback * pCallback, IN OPTIONAL UINT uID)
	{
		DWORD dwUIThreadId,dwLogicThreadId,dwCurrentThreadId;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		dwCurrentThreadId = GetCurrentThreadId();
		
		//如果主线程消息循环已经退出,直接返回.
		//没办法,全局对象析构依赖,比较坑爹！！！
		if(IsMainThreadLoopQuit()) return FALSE;

		if(dwCurrentThreadId != dwUIThreadId && dwCurrentThreadId != dwLogicThreadId)
		{
			TXTimerThreadWarnning();
			return FALSE;
		}
		else
		{
			if(!GetInst(dwCurrentThreadId)->EraseTimerCallback(pCallback, uID) )
			{
				DWORD dwId = (dwCurrentThreadId == dwUIThreadId)? dwLogicThreadId : dwUIThreadId;
				CTimerDetail* pInst = FindTimerInst(dwId);
				if (pInst)
				{
					return pInst->EraseTimerCallback(pCallback, uID);
				}	
			}
			else
				return TRUE;
		}
		return FALSE;
	}
	/** 注销一个已经设置的Idle Callback
	*
	*	@param pCallback   in, 回调接口
	*
	*	@retval TRUE		成功
	*	@retval FALSE		失败
	*/
	BOOL EraseIdleCallback(ITXIdleCallback * pCallback, UINT uID)
	{
		DWORD dwUIThreadId,dwLogicThreadId,dwCurrentThreadId;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		dwCurrentThreadId = dwUIThreadId;
		
		//如果主线程消息循环已经退出,直接返回.
		//没办法,全局对象析构依赖,比较坑爹！！！
		if(IsMainThreadLoopQuit()) return FALSE;
		
		//idle只有主线程才有意义,可能会操作GF对象
		return GetInst(dwCurrentThreadId)->EraseIdleCallback(pCallback, uID);
	}
	/** 下次idle时调用接口。
	*
	*	@param pCallback   in, 回调接口
	*
	*	@retval TRUE		成功
	*	@retval FALSE		失败
	*/
	BOOL SetIdleCallback(ITXIdleCallback * pCallback, UINT uID)
	{
		DWORD dwUIThreadId,dwLogicThreadId,dwCurrentThreadId;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		dwCurrentThreadId = dwUIThreadId;
		return GetInst(dwCurrentThreadId)->NextIdleCall(pCallback, uID);
	}

	/** 仅给消息循环处调用的idle通知器。
	*/
	VOID NotifyIdle()
	{
		DWORD dwCurrentThreadId = GetCurrentThreadId();
		return GetInst(dwCurrentThreadId)->NotifyIdle();
	}

	BOOL SetAsyncCallback(IN ITXAsyncCallback * pCallback, IN OPTIONAL UINT uID)
	{
		DWORD dwUIThreadId,dwLogicThreadId;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		return GetInst(dwUIThreadId)->SetAsyncCallback(pCallback, uID);
	}

	BOOL SetAsyncCallback(void (__stdcall *pCallback)(PVOID vParam), PVOID vParam)
	{
		DWORD dwUIThreadId,dwLogicThreadId;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		return GetInst(dwUIThreadId)->SetAsyncCallback(pCallback, vParam);
	}

	BOOL EraseAsyncCallback(IN ITXAsyncCallback * pCallback, IN OPTIONAL UINT uID)
	{
		DWORD dwUIThreadId,dwLogicThreadId;
		//如果主线程消息循环已经退出,直接返回.
		//没办法,全局对象析构依赖,比较坑爹！！！
		if(IsMainThreadLoopQuit()) return FALSE;
		Util::Misc::GetMainAndLogicThreadId(dwUIThreadId,dwLogicThreadId);
		return GetInst(dwUIThreadId)->EraseAsyncCallback(pCallback, uID);
	}
};